<?php

namespace app\api\controller\fruit\v22;

use app\api\model\fruit\warrior\Achieve;
use app\api\model\fruit\warrior\User;

/**
 * @author zero
 * @Time 2019/3/2
 *
 * Class Warrioruser
 * @package app\api\controller\fruit\v22
 *
 * 切水果勇士用户接口 v22
 */
class Warrioruser extends Warrior
{

    protected $noNeedLogin = ["login"];

    // 首页展示的跳转其它小程序(新)
    protected $new_list = array(
        array(
            'name' => '游趣娱乐',
            'appid' => 'wxa9002f27f3ed1519',
            'icon' => 'https://xcx-1256535092.cos.ap-shanghai.myqcloud.com/game/icon/you.jpg'
        ),
        array(
            'name' => '萌消团',
            'appid' => 'wxd26399f7e0a403d0',
            'icon' => 'https://xcx-1256535092.cos.ap-shanghai.myqcloud.com/jingpinhezi/icon/mxt.png'
        ),
        array(
            'name' => '一起来合体',
            'appid' => 'wxd382be58d8c6d6c9',
            'icon' => 'https://xcx-1256535092.cos.ap-shanghai.myqcloud.com/jingpinhezi/icon/heti.png'
        ),
        array(
            'name' => '一起飞飞飞',
            'appid' => 'wxe42ac5dd0f116b26',
            'icon' => 'https://xcx-1256535092.cos.ap-shanghai.myqcloud.com/jingpinhezi/icon/fly.jpg'
        )
    );

    // 登录接口
    public function login()
    {
        $gh_id = $this->request->post('gh_id');
        $code = $this->request->post('code');
        // 拿到微信服务器返回数据
        $data = $this->jscode2session($gh_id, $code);
        if ($data) {
            $openid = $data['openid'];
            $session_key = $data['session_key'];
            $token = md5(md5($openid) . $session_key); // token

            $user = User::get(['openid' => $openid]);
            if (!$user) {
                $user = new User;
                $user->level = 0;
                $user->coin = 0;
                $user->weapon_v2 = 1;
                $user->weapon_list_v2 = '1';
            }
            $user->openid = $openid;
            $user->session = $session_key;
            $user->token = $token;
            $user->save();
            // 判断是否有成就表记录
            $achieves = Achieve::get(['user_id' => $user->id]);
            if (!$achieves) {
                $achieves = new Achieve();
                $achieves->user_id = $user->id;
                $achieves->openid = $openid;
                $achieves->level = $user->level;
                $achieves->save();
            }

            $return['token'] = $token;
            $this->result('login', $return);
        }
        $this->error('error');
    }

    // 获取用户信息
    public function get_user_info()
    {
        $data = [
            'openid' => $this->user->openid, // openid
            'nick_name' => $this->user->nick_name ?: '', // 昵称
            'avatar_url' => $this->user->avatar_url ?: '', // 头像
            'level' => $this->user->level + 1, // 关卡数
            'coin' => $this->user->coin, // 金币
            'diamond' => $this->user->diamond, //钻石
            'weapon' => $this->get_use_exp_weapon() ?: $this->user->weapon_v2, // 当前使用武器,并判断是否有试用的武器
            'week_lucky' => $this->user->week_lucky, // 本周中奖状态
            'invite_award' => $this->user->invite_award ? true : false, // 是否领取过邀请奖励
            'is_sign_in' => $this->user->is_sign_in ? true : false, // 当天是否签到
            'offline_money' => $this->handle_offline_income(), // 离线收益
            'enter_xcx_award' => $this->user->enter_xcx_award ? true : false, // 是否领取过我的小程序进入奖励
            'first_enter' => false, // 当天第一次进入
            'first_week_enter' => false, // 当周第一次进入
            'achieve' => $this->achieve(), // 是否有成就为领取
            'important_list' => $this->compare_version($this->version, '2.2.7') >= 0 ? $this->new_list : $this->important_list, // 首页展示跳转小程序
            'flag' => $this->version == $this->control_version ? true : false, // 审核控制
        ];

        // 判断今天是否第一次登录
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y')); // 今天0点
        if ($this->user->last_logout_time < $beginToday) {
            // 处理登录天数成就
            $this->handle_achieve('login_num');
            $this->user->is_sign_in = 0; // 签到清空
            $this->user->endless_ticket_num = 2; // 每天送入场券
            $this->user->save();
            $data['is_sign_in'] = false;
            $data['first_enter'] = true;
            // 判断本周是否第一次弹出
            $beginWeek = $beginToday - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600; // 本周一0点
            if ($this->user->last_logout_time < $beginWeek) {
                $data['first_week_enter'] = true;
            }
        }

        $this->result('data', $data);
    }

    // 更新玩家头像昵称
    public function update_user_info()
    {
        $nick_name = $this->request->post('nick_name');
        $avatar_url = $this->request->post('avatar');
        if ($nick_name && $nick_name !== '') {
            $this->user->nick_name = $nick_name;
        }
        if ($avatar_url && $avatar_url !== '') {
            $this->user->avatar_url = $avatar_url;
        }
        $this->user->save();
        $this->result('ok');
    }

    // 普通关卡结算
    public function balance()
    {
        // 根据关卡数,进行奖励发放
        $level = $this->request->post('level') ?: 0;
        $fruit_list = $this->request->post('fruit_list');
        $one_cut_num = $this->request->post('one_cut_num') ?: 0;
        $current_weapon = $this->request->post('current_weapon') ?: $this->user->weapon_v2;
        // 处理结算成就
        $this->handle_balance_achieve($one_cut_num, $fruit_list);
        // 计算关卡收益
        $ceil_10 = ceil($level / 10); // 除10后向上取整
        $remainder_10 = floor($level % 10); // 10的余数
        $coin = $ceil_10 * 5 + 20;
        $diamond = $ceil_10 * 2 - 1;
        // 每隔几关赠送一张无尽模式入场券
        if ($level % $this->ticket_level == 0) {
            $this->user->endless_ticket_num += 1;
        }
        // 特殊武器收益处理
        $percent = 0;
        $weapon_define = $this->get_weapon_define();
        $weapon = $weapon_define->$current_weapon;
        if ($weapon->score_probability && $weapon->change_percent) {
            if ($weapon->score_probability == 1) {
                $symbol = 1;
            } elseif ($weapon->score_probability == 2) {
                $symbol_arr = [-1, 1];
                $symbol = $symbol_arr[array_rand($symbol_arr)];
            }
            $percent = $symbol * $weapon->change_percent / 100;
        }
        // 根据关卡数控制武器获取和倍数
        $multiple = 2; // 倍数
        $get_weapon = 0; // 可获取武器
        $have_weapon_list = array_unique(explode(',', $this->user->weapon_list_v2));
        if ($level == 5) {
            $multiple = 10;
        }
        if ($level == 7) {
            $get_weapon = $this->get_free_weapon($have_weapon_list, $weapon_define);
        }
        if ($ceil_10 > 1 && $remainder_10 == 0) {
            $multiple = 5;
            if ($ceil_10 % 2 != 0) {
                $multiple = 10;
            }
            $rand = mt_rand(1, 8);
            if ($rand == 8) {
                $get_weapon = $this->get_free_weapon($have_weapon_list, $weapon_define);
            }
        }
        // 更新用户数据
        $coin = floor($coin * (1 + $percent));
        $diamond = floor($diamond * (1 + $percent));
        $this->user->coin += $coin;
        $this->user->diamond += $diamond;
        $this->user->level = $level;
        if ($this->user->save() !== false) {
            $data = [
                'coin' => $coin,
                'diamond' => $diamond,
                'percent' => $percent,
                'multiple' => $multiple,
                'get_weapon' => $get_weapon
            ];
            $this->result('ok', $data);
        }
        $this->error('fail');
    }

    // 取出免费得到的武器
    public function get_free_weapon($have_weapon_list, $weapon_define)
    {
        for ($i = 19; $i <= 23; $i++) {
            if (!in_array($i, $have_weapon_list)) {
                return [
                    'id' => $i,
                    'path' => $weapon_define->$i->getpath
                ];
            }
        }
    }

    // 翻倍结算
    public function multiple_balance()
    {
        $multiple = intval($this->request->post('multiple'));
        $coin = intval($this->request->post('coin'));
        $diamond = intval($this->request->post('diamond'));

        $coin = floor($coin * ($multiple - 1));
        $diamond = floor($diamond * ($multiple - 1));

        $this->user->coin += $coin;
        $this->user->diamond += $diamond;
        if ($this->user->save() !== false) {
            $data['coin'] = $coin;
            $data['diamond'] = $diamond;
            $this->result('ok', $data);
        } else {
            $this->error('fail');
        }
    }

    // 处理邀请用户
    public function handle_invite()
    {
        $from_openid = $this->request->post('from_openid');
        if ($from_openid) {
            $from_user = User::get(['openid' => $from_openid]); // 来源用户
            // 未领取奖励
            if ($from_user && $from_user->invite_award == 0) {
                $invite_openid = $this->user->openid; // 被邀请用户openid
                $invite_list = explode(',', $from_user->invite_info);
                // 邀请数小于5
                if (count($invite_list) < 5) {
                    if (!$from_user->invite_info) {
                        $from_user->invite_info = $invite_openid;
                    } else {
                        foreach ($invite_list as $item) {
                            if ($item == $invite_openid) {
                                return;
                            }
                        }
                        $from_user->invite_info = $from_user->invite_info . ',' . $invite_openid;
                    }
                    $from_user->save();
                    return;
                }
            }
        }
        return;
    }

    // 更新用户最后登出时间
    public function update_logout_time()
    {
        $this->user->last_logout_time = time();
        $this->user->save();
        $this->success('ok');
    }

    // 领取离线收益
    public function get_offline_money()
    {
        $multiple = $this->request->post('multiple') ?: 1; // 翻倍
        $offline_money = $this->handle_offline_income() * $multiple;
        $this->user->diamond += $offline_money;
        if ($this->user->save() !== false) {
            $this->result('ok', 'a_2_' . $offline_money);
        } else {
            $this->error('fail');
        }
    }

    // 获取世界排行榜数据
    public function global_rank()
    {
        $type = $this->request->param('type');
        $page = $this->request->param('page') ?: 1;
        switch ($type) {
            case 'normal':
                $field = 'level';
                break;
            case 'endless':
                $field = 'endless_score';
                break;
            default:
                $field = 'level';
                break;
        }
        // 全球排行
        $rank_list = User::whereNotNull('avatar_url')->limit(($page - 1) * 20, 20)->order($field, 'desc')->select();
        $global_rank = array();
        foreach ($rank_list as $key => $item) {
            $global_rank[] = ['nick_name' => $item->nick_name, 'avatar_url' => $item->avatar_url, $field => $item->$field, 'rank_id' => $key + 1];
        }
        // 个人排行
        $list = User::whereNotNull('avatar_url')->limit(0, 100)->order($field, 'desc')->select();
        $rank_id = 0;
        // 对比当前用户id
        foreach ($list as $key => $item) {
            if ($item->openid == $this->user->openid) {
                $rank_id = $key + 1;
                break;
            }
        }
        $self_rank = ['nick_name' => $this->user->nick_name, 'avatar_url' => $this->user->avatar_url, $field => $this->user->$field, 'rank_id' => $rank_id];

        $data['global_rank'] = $global_rank;
        $data['self_rank'] = $self_rank;
        $this->result('ok', $data);
    }

    // 获取周榜中奖数据
    public function get_week_lucky()
    {
        $data['self'] = $this->user->week_lucky;
        switch ($data['self']) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                $data['money'] = 200;
                $data['wx'] = 'WXTT0417';
                break;
            default:
                $data['money'] = 0;
                $data['wx'] = '';
                break;
        }
        $this->result('ok', $data);
    }

    // 中奖者跑马灯数据
    public function get_lucky_marquee()
    {
        $marquee = User::whereIn('week_lucky', '1,2,3,4,5')->column('phone_number');
        $this->result('ok', $marquee);
    }

    // 复活
    public function resurrect()
    {
        $cost = $this->request->post('cost');
        if ($cost && $this->handle_cost($cost)) {
            if ($this->user->save() !== false) {
                $data['coin'] = $this->user->coin;
                $data['diamond'] = $this->user->diamond;
                $this->result('ok', $data);
            }
        }
        $this->result('fail');
    }

    // 处理结算成就
    public function handle_balance_achieve($one_cut_num, $fruit_list)
    {
        $achieves = Achieve::get(['user_id' => $this->user->id]);
        if ($achieves) {
            if ($achieves->one_cut_num != 'complete' && $achieves->one_cut_num != 'get') {
                $achieves->one_cut_num = $achieves->one_cut_num + $one_cut_num;
            }
            if ($achieves->level != 'complete' && $achieves->level != 'get') {
                $achieves->level = $this->user->level;
            }
            if ($fruit_list) {
                $fruit_list = json_decode($fruit_list, true);
                foreach ($fruit_list as $key => $value) {
                    $fruit = 'fruit_' . $key;
                    if ($achieves->$fruit != 'complete' && $achieves->$fruit != 'get') {
                        $achieves->$fruit = $achieves->$fruit + $value;
                    }
                }
            }
        }
        $achieves->save();
    }

    // 查询成就信息
    public function achieve_info()
    {
        $achieve_define = $this->get_achieve_define();
        $user_achieves = Achieve::get(['user_id' => $this->user->id]);
        $list = [];
        foreach ($achieve_define as $id => $achieve) {
            if ($achieve && $achieve->condition) {
                $list[$id] = $this->handle_achieve_condition($user_achieves, $achieve->condition);
            }
        }
        $user_achieves->save();
        $this->result('ok', $list);
    }

    // 领取成就奖励
    public function get_achieve_award()
    {
        $id = $this->request->param('id'); // 成就id
        $keyword = $this->request->param('keyword'); // 成就关键字
        $achieve_define = $this->get_achieve_define(); // 取出成就json数据
        $user_achieve = Achieve::get(['user_id' => $this->user->id]); // 取出个人成就数据
        // 当这个成就为完成时
        if ($user_achieve && $user_achieve->$keyword == 'complete') {
            $achieve = $achieve_define->$id;

            if ($achieve && $achieve->keyword == $keyword && $achieve->award) {
                // 处理奖励
                $this->handle_award($achieve->award);
                // 标记成就已领取奖励
                $user_achieve->$keyword = 'get';
                // 更新数据库
                if ($user_achieve->save() !== false && $this->user->save() !== false) {
                    $this->result('ok', [
                        'award' => $achieve->award,
                        'achieve' => $this->achieve()
                    ]);
                }
            }
        }
        $this->result('fail');
    }

}
